package com.ocom.common.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.binarywang.utils.qrcode.MatrixToImageWriter;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;

public class QRCodeUtil {
    private static String base64Url = "data:image/png;base64,";

    /**
     * 创建二维码
     *
     * @param url
     * @param fileName
     * @return
     * @throws IOException
     * @throws WriterException
     */
    public static String createQRCode(String json,Integer width,Integer height) throws IOException, WriterException {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();

//        QrConfig config = new QrConfig(1000, 1000);
//        config.setMargin(1);


        HashMap<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        hints.put(EncodeHintType.MARGIN, 0);//二维码空白区域,最小为0也有白边,只是很小,最小是6像素左右


        BitMatrix bitMatrix = qrCodeWriter.encode(json, BarcodeFormat.QR_CODE, width, height, hints);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        MatrixToImageWriter.writeToStream(bitMatrix, "PNG", outputStream);
        Base64.Encoder encoder = Base64.getEncoder();
        String text = encoder.encodeToString(outputStream.toByteArray());
        return base64Url + text;
    }

    public static void main(String[] args) throws IOException, WriterException {
        JSONObject json = new JSONObject();
        JSONArray arr = new JSONArray();
        json.put("name", "吴顺杰");
        json.put("phone", "手机号码");
        json.put("address", "地址");
        json.put("bookid", "64");
        for (int i = 0; i < 3; i++) {
            JSONObject jsonw = new JSONObject();
            jsonw.put("id", i);
            jsonw.put("count", i);
            jsonw.put("remake", "哈哈哈");
            arr.add(jsonw);
            json.put("Books", arr);

        }
        System.out.println(json);
        System.out.println(createQRCode(json.toString(),100,100));
    }
}
